package com.gitee.kenewstar.migration.function;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.gitee.kenewstar.migration.constants.Const;
import com.gitee.kenewstar.migration.constants.FunctionCode;
import com.gitee.kenewstar.migration.core.AbstractSyncFunction;
import com.gitee.kenewstar.migration.core.ContextParam;
import com.gitee.kenewstar.migration.entity.CommonResult;
import com.gitee.kenewstar.migration.entity.Prompt;
import com.gitee.kenewstar.migration.service.MulLanguageService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 前端多语言
 * @author kenewstar
 */
@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class PromptFunction extends AbstractSyncFunction<Prompt> {

    private final MulLanguageService mulLanguageService;

    @Override
    protected Class<Prompt> parameterType() {
        return Prompt.class;
    }

    @Override
    public List<CommonResult> execute(ContextParam contextParam, List<Prompt> list) {
        final List<String> prefixValue = getParameterList("prefixLike");
        final List<Prompt> promptList = this.mulLanguageService.devSelectPromptByLike(prefixValue);
        promptList.addAll(this.mulLanguageService.devSelectPromptList(list));
        if (CollUtil.isEmpty(promptList)) {
            return Collections.emptyList();
        }

        List<CommonResult> resultList = new ArrayList<>(10);
        for (Prompt prompt : promptList) {
            CommonResult result = CommonResult.create(true)
                    .setPromptKey(prompt.getPromptKey()).setPromptCode(prompt.getPromptCode())
                    .setLang(prompt.getLang()).setTenantId(prompt.getTenantId());
            try {
                this.mulLanguageService.uatInsertPrompt(prompt);
            } catch (Exception e) {
                result.setSuccessFlag(false).setErrorMsg(e.getMessage());
                e.printStackTrace();
            } finally {
                resultList.add(result);
            }
        }

        return resultList;
    }

    @Override
    public FunctionCode functionCode() {
        return FunctionCode.PROMPT;
    }

    @Override
    @DS(Const.UAT)
    @Transactional(rollbackFor = Exception.class)
    public void singleExecute(ContextParam contextParam) {

    }
}
